package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.example.dto.dept.Dept;
import com.example.dto.dept.DeptCriteria;
import com.example.exception.BadRequestException;
import com.example.server.DeptServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "系统：部门管理")
@RequestMapping("/api/dept")
public class DeptController {

    @Autowired
    private DeptServer deptServer;
    private static final String ENTITY_NAME = "dept";

    @ApiOperation("查询部门")
    @GetMapping
    public ResponseEntity<Object> list(DeptCriteria criteria){
        Map<String, Object> result = new HashMap<>(4);
        List<Dept> list =  deptServer.list(criteria);
        result.put("content",list);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @ApiOperation("查询部门:根据ID获取同级与上级数据")
    @PostMapping("/superior")
    public ResponseEntity<Object> getDeptSuperior(@RequestBody List<Long> ids) {
        Set<Dept> deptDtos  = new LinkedHashSet<>();
        for (Long id : ids) {
            Dept deptDto = deptServer.findById(id);
            List<Dept> depts = deptServer.getSuperior(deptDto, new ArrayList<>());
            deptDtos.addAll(depts);
        }
        return new ResponseEntity<>(deptServer.buildTree(new ArrayList<>(deptDtos)),HttpStatus.OK);
    }

    @ApiOperation("新增部门")
    @PostMapping
    public ResponseEntity<Object> createDept(@RequestBody Dept resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        deptServer.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @ApiOperation("删除部门")
    @DeleteMapping
    public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids) {
        Set<Dept> deptDtos = new HashSet<>();
        for (Long id : ids) {
            List<Dept> deptList = deptServer.findByPid(id);
            deptDtos.add(deptServer.findById(id));
            if (CollectionUtil.isNotEmpty(deptList)) {
                deptDtos = deptServer.getDeleteDepts(deptList, deptDtos);
            }
        }
        deptServer.delete(deptDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改部门")
    @PutMapping
    public ResponseEntity<Object> updateDept(@RequestBody Dept resources){
        deptServer.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}
